package com.tfj.mvp.tfj.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.flyco.tablayout.SlidingTabLayout;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.hyphenate.tfj.DemoApplication;
import com.hyphenate.tfj.R;
import com.tfj.comm.fragment.BannerFragmentRound;
import com.tfj.mvp.base.BaseFragment;
import com.tfj.mvp.tfj.home.adapter.LatestAdapter;
import com.tfj.mvp.tfj.home.adapter.LiveHomeAdapter;
import com.tfj.mvp.tfj.home.arround.VArroundActivity;
import com.tfj.mvp.tfj.home.bean.AdBean;
import com.tfj.mvp.tfj.home.bean.HouseDataBean;
import com.tfj.mvp.tfj.home.bean.LatestBean;
import com.tfj.mvp.tfj.home.houselist.VHouseListActivity;
import com.tfj.mvp.tfj.home.news.VNewsListActivity;
import com.tfj.mvp.tfj.live.bean.LiveBean;
import com.tfj.mvp.tfj.home.shop.VShopShowListActivity;
import com.tfj.utils.AntiShakeUtils;
import com.tfj.utils.SysUtils;
import com.tfj.utils.ViewFindUtils;
import com.tfj.widget.RoundAngleImageView;
import com.zhuang.zbannerlibrary.ZBanner;
import com.zhuang.zbannerlibrary.ZBannerAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by HuangQiang on 2017/12/21.
 *
 * @author HuangQiang
 * @github https://github.com/HuangQiang
 */

public class VHomeFragment extends BaseFragment<PHomeImpl> implements CHome.IVHome, AMapLocationListener {

    @BindView(R.id.rl_left2)
    RelativeLayout rlLeft2;
    @BindView(R.id.imageView_recom_1)
    RoundAngleImageView imageViewRecom1;
    @BindView(R.id.imageView_recom_2)
    RoundAngleImageView imageViewRecom2;
    @BindView(R.id.recyclew_live)
    RecyclerView recyclewLive;
    @BindView(R.id.recyclerView_latest)
    RecyclerView recyclerViewLatest;
    @BindView(R.id.textView_city)
    TextView textViewCity;
    @BindView(R.id.ll_btn_live)
    LinearLayout llBtnLive;
    @BindView(R.id.ll_btn_newhouse)
    LinearLayout llBtnNewhouse;
    @BindView(R.id.ll_btn_arround)
    LinearLayout llBtnArround;
    @BindView(R.id.ll_btn_shop)
    LinearLayout llBtnShop;
    private ArrayList<Fragment> mFragments_rank = new ArrayList<>();
    private MyPagerAdapter_Rank mAdapter = null;
    private ArrayList<Fragment> mFragments_type = new ArrayList<>();
    private MyPagerAdapter_Type mAdapter_type = null;
    @BindView(R.id.zBanner)
    ZBanner zBanner;
    @BindView(R.id.iamgeView_left)
    RoundAngleImageView iamgeViewLeft;
    @BindView(R.id.iamgeView_top1)
    RoundAngleImageView iamgeViewTop1;
    @BindView(R.id.iamgeView_top2)
    RoundAngleImageView iamgeViewTop2;
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.rl_top1)
    RelativeLayout rlTop1;
    @BindView(R.id.rl_top2)
    RelativeLayout rlTop2;
    @BindView(R.id.rl_news)
    RelativeLayout rlNews;
    private final String[] mTitles = {
            "排行榜", "热门直播榜",
    };
    private final String[] mTitles_type = {
            "新房", "商铺",
    };
    List<AdBean.DataBean> beans = new ArrayList<AdBean.DataBean>();
    private LiveHomeAdapter liveAdapter = null;
    private LatestAdapter latestAdapter = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    //声明定位回调监听器
    public static VHomeFragment newInstance() {
        VHomeFragment fragment = new VHomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        //最热直播
        LinearLayoutManager linearLayoutManager_live = new LinearLayoutManager(getActivity());
        linearLayoutManager_live.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclewLive.setLayoutManager(linearLayoutManager_live);
        liveAdapter = new LiveHomeAdapter(getActivity());
        recyclewLive.setAdapter(liveAdapter);
        List<LiveBean> liveBeans = new ArrayList<>();
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveBeans.add(new LiveBean());
        liveAdapter.replaceData(liveBeans);
        //最新新盘
        LinearLayoutManager linearLayoutManager_latest = new LinearLayoutManager(getActivity());
        linearLayoutManager_latest.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewLatest.setLayoutManager(linearLayoutManager_latest);
        latestAdapter = new LatestAdapter(getActivity());
        recyclerViewLatest.setAdapter(latestAdapter);
        List<LatestBean> latestBeans = new ArrayList<>();
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestBeans.add(new LatestBean());
        latestAdapter.replaceData(latestBeans);
        //初始化图片尺寸
        int size = SysUtils.getScreenWidth(getActivity()) / 2 - SysUtils.dip2px(getActivity(), 48) / 2;
        ViewGroup.LayoutParams layoutParams_left = rlLeft.getLayoutParams();
        ViewGroup.LayoutParams layoutParams_left2 = rlLeft2.getLayoutParams();
        ViewGroup.LayoutParams layoutParams_imageViewRecom1 = imageViewRecom1.getLayoutParams();
        ViewGroup.LayoutParams layoutParams_imageViewRecom2 = imageViewRecom2.getLayoutParams();
        ViewGroup.LayoutParams layoutParams_top1 = rlTop1.getLayoutParams();
        ViewGroup.LayoutParams layoutParams_top2 = rlTop2.getLayoutParams();
        layoutParams_left2.width = size;
        layoutParams_left.height = size;
        layoutParams_left.width = size;
        layoutParams_top1.width = size;
        layoutParams_top2.width = size;
        int height = (size - SysUtils.dip2px(getActivity(), 16)) / 2;
        int imageWidth = SysUtils.getScreenWidth(getActivity()) / 4 - SysUtils.dip2px(getActivity(), 64) / 4;
        layoutParams_top1.height = height;
        layoutParams_top2.height = height;
        layoutParams_imageViewRecom1.width = imageWidth;
        layoutParams_imageViewRecom2.width = imageWidth;
        rlTop1.setLayoutParams(layoutParams_top1);
        rlLeft.setLayoutParams(layoutParams_left);
        rlTop2.setLayoutParams(layoutParams_top2);
        rlLeft2.setLayoutParams(layoutParams_left2);
        imageViewRecom1.setLayoutParams(layoutParams_imageViewRecom1);
        imageViewRecom2.setLayoutParams(layoutParams_imageViewRecom2);
        //动画
        ViewAnimator.animate(rlNews, rlNews)
                .rotationX(0, -15, 15, 360).duration(3000).repeatCount(1000).onStart(new AnimationListener.Start() {
            @Override
            public void onStart() {
                Log.i(TAG, "开始");
            }
        })
                .start();
        renderBanner();
        initLocation();
    }

    private void initLocation() {
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置为单次定位
        option.setOnceLocation(true);
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationClient = new AMapLocationClient(DemoApplication.getInstance());
//设置定位回调监听
        mLocationClient.setLocationListener(this);
        if (null != mLocationClient) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                //没有权限，向系统申请该权限。
                Log.i(TAG, "没有权限");
                //这里添加向系统请求权限操作
            } else {
                //已经获得权限，则执行定位请求。
                mLocationClient.setLocationOption(option);
                //mLocationClient，再调用start以保证场景模式生效
                mLocationClient.stopLocation();
                mLocationClient.startLocation();
                Log.i(TAG, "开始定位");
            }

        }
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_home;
    }

    @Override
    public void createPresenter() {
        mPresenter = new PHomeImpl(mContext, this);
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //排行viewpager
        List<HouseDataBean> houseDataBeans_rank = new ArrayList<>();
        houseDataBeans_rank.add(new HouseDataBean());
        houseDataBeans_rank.add(new HouseDataBean());
        houseDataBeans_rank.add(new HouseDataBean());
        houseDataBeans_rank.add(new HouseDataBean());
        houseDataBeans_rank.add(new HouseDataBean());
        for (String title : mTitles) {
            mFragments_rank.add(new VFragmentRank(houseDataBeans_rank));
        }
        View decorView = getActivity().getWindow().getDecorView();
        ViewPager vp_rank = ViewFindUtils.find(decorView, R.id.vp_rank);
        mAdapter = new MyPagerAdapter_Rank(getChildFragmentManager());
        vp_rank.setAdapter(mAdapter);
        SlidingTabLayout tabLayout = ViewFindUtils.find(decorView, R.id.tl_rank);
        tabLayout.setViewPager(vp_rank);
        vp_rank.setCurrentItem(0);
        //类型viewpager
        List<HouseDataBean> houseDataBeans = new ArrayList<>();
        houseDataBeans.add(new HouseDataBean());
        houseDataBeans.add(new HouseDataBean());
        houseDataBeans.add(new HouseDataBean());
        houseDataBeans.add(new HouseDataBean());
        houseDataBeans.add(new HouseDataBean());
        for (String title : mTitles_type) {
            mFragments_type.add(new VFragmentType(houseDataBeans));
        }
        View decorView1 = getActivity().getWindow().getDecorView();
        ViewPager vp_type = ViewFindUtils.find(decorView1, R.id.vp_type);
        mAdapter_type = new MyPagerAdapter_Type(getChildFragmentManager());
        vp_type.setAdapter(mAdapter_type);
        SlidingTabLayout tl_type = ViewFindUtils.find(decorView1, R.id.tl_type);
        tl_type.setViewPager(vp_type);
        vp_type.setCurrentItem(0);

    }

    public void renderBanner() {
        beans.add(new AdBean.DataBean());
        beans.add(new AdBean.DataBean());
        beans.add(new AdBean.DataBean());
        if (beans != null && beans.size() > 0) {
            zBanner.setAdapter(new MyBannerAdapter1(getChildFragmentManager()));
            zBanner.star();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (beans != null && beans.size() > 0) {
            zBanner.star();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        zBanner.stop();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation.getErrorCode() == 0) {
            Log.i(TAG, "城市信息--->" + amapLocation.getCity() + "城区信息--->" + amapLocation.getDistrict());
            textViewCity.setText(amapLocation.getCity());
        } else {
            textViewCity.setText("定位失败");
            Log.e("AmapError", "location Error, ErrCode:"
                    + amapLocation.getErrorCode() + ", errInfo:"
                    + amapLocation.getErrorInfo());
        }

    }

    @OnClick({R.id.ll_btn_live, R.id.ll_btn_newhouse, R.id.ll_btn_arround, R.id.ll_btn_shop,R.id.rl_news})
    public void onViewClicked(View view) {
        if(AntiShakeUtils.isInvalidClick(view)){
            return;
        }
        switch (view.getId()) {
            case R.id.ll_btn_live:
                break;
            case R.id.ll_btn_newhouse:
                Intent intent = new Intent(getActivity(), VHouseListActivity.class);
                intent.putExtra("title","新房");
                startActivity(intent);
                break;
            case R.id.ll_btn_arround:
                startActivity(VArroundActivity.class);
                break;
            case R.id.ll_btn_shop:
                startActivity(VShopShowListActivity.class);
                break;
            case R.id.rl_news:
                startActivity(VNewsListActivity.class);
                break;
        }
    }

    //轮播适配器
    private class MyBannerAdapter1 extends ZBannerAdapter {

        public MyBannerAdapter1(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return BannerFragmentRound.newInstance(beans.get(position), position, getActivity(), true);
        }

        @Override
        public int getCount() {
            return beans.size();
        }
    }

    //排名切换 适配器
    private class MyPagerAdapter_Rank extends FragmentPagerAdapter {
        public MyPagerAdapter_Rank(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments_rank.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments_rank.get(position);
        }
    }

    //类型切换 适配器
    private class MyPagerAdapter_Type extends FragmentPagerAdapter {
        public MyPagerAdapter_Type(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments_type.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles_type[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments_type.get(position);
        }
    }
}
